package org.jaronsource.framework.core.dao.support;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class EntityUtils {

	public static boolean isNew( Serializable pk ) {

		if ( pk == null ) return true;

		if ( pk instanceof Integer ) { return ( (Integer) pk ).intValue() == 0; }

		if ( pk instanceof Long ) { return ( (Long) pk ).intValue() == 0; }

		return false;
	}

	/**
	 * 按模式加载延迟的对象
	 * <p>
	 * 用法：
	 * 
	 * <pre>
	 * EntityUtils.touch( user, &quot;dept&quot; ); // dept 是user对象的字段 EntityUtils.touch( item,
	 * &quot;sale.inputUser&quot; ); // sale 是item对象的字段，inputUser // 是sale对象的字段
	 * </pre>
	 * 
	 * @param source 含有延迟加载的对象
	 * @param pattern 模式
	 */
	public static void touch( Object source, String pattern ) {

		String[] patternFrags = StringUtils.split( pattern, "." );
		Object obj = source;
		Class<?> clazz = source.getClass();
		for ( String patternFrag : patternFrags ) {
			try {
				if ( obj != null ) {

					obj.toString();

					Object value = null;
					Method method = clazz.getDeclaredMethod( "get" + patternFrag.substring( 0, 1 ).toUpperCase() + patternFrag.substring( 1 ) );
					if ( method != null ) {
						String fieldName = method.getName().substring( 3 );
						fieldName = fieldName.substring( 0, 1 ).toLowerCase() + fieldName.substring( 1 );

						if ( fieldName.equals( patternFrag ) ) {
							value = method.invoke( obj );
							if ( value != null ) value.toString();
						}
					}

					obj = value;
				}
				else {
					break;
				}
			}
			catch ( Exception e ) {
				obj = null;
				break;
			}
		}
	}

	public static void touch( List<?> sources, String pattern ) {
		for ( Object source : sources ) {
			touch( source, pattern );
		}
	}

}
